package org.cabbage.lintcode;

import java.math.BigDecimal;

public class Atoi {

    public static void main(String[] args) {

        Atoi atoi = new Atoi();
        System.out.println(atoi.atoi("-1.0"));

    }

    public int atoi(String str) {
        if (str == null) return 0;
        StringBuilder sb = new StringBuilder();
        boolean hasBegin = false;
        boolean minus = false;

        for (int i = 0; i < str.length(); i++) {
            String s = String.valueOf(str.charAt(i));
            if (s.equals("-") && !hasBegin && !minus) {
                minus = true;
            }
            if (s.compareTo("0") >= 0 && s.compareTo("9") <= 0) {
                if (s.equals("0") && !hasBegin) {
                    continue;
                }
                sb.append(s);
                hasBegin = true;
            }
            if (s.equals(".")) {
                break;
            }
        }
        if (sb.length() == 0) {
            return 0;
        }

        try {
            BigDecimal source = minus ? new BigDecimal("-" + sb.toString()) : new BigDecimal(sb.toString());
            if (source.compareTo(new BigDecimal(Integer.MAX_VALUE)) > 0) {
                return Integer.MAX_VALUE;
            }
            if (source.compareTo(new BigDecimal(Integer.MIN_VALUE)) < 0) {
                return Integer.MIN_VALUE;
            }
            return source.intValue();
        } catch (Exception ex) {
            return 0;
        }
    }
}
